﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Script.Serialization;
using System.Xml;
using bmapi.HelperClass;
using bmapi.Models.DataEntity;
using bmapi.SQLServerAccess;
using Jose;
using static bmapi.HelperClass.AssistFun;

namespace bmapi.Controllers
{
    public class BuyiController : ApiController
    {
        protected string m_buyiRoot = HttpContext.Current.Server.MapPath("/buyiRoot");
        //protected static string filePath = HttpContext.Current.Server.MapPath("~/buyiRoot");        


        #region 操作 token
        /// <summary>
        /// 生成token
        /// </summary>
        /// <param name="loginid"></param>
        /// <returns></returns>
        protected string CreateToken(int loginid)
        {
            string secret = ConfigurationManager.AppSettings["secret"];
            string token = "";
            var payload = new JwtAuthObject()
            {
                LoginID = loginid
            };
            //生成 token 
            token = JWT.Encode(payload, Encoding.UTF8.GetBytes(secret), JwsAlgorithm.HS256);
            return token;
        }
        /// <summary>
        ///  从Token中获取登陆者数据
        /// </summary>
        protected int GetCrrentIDByToken()
        {
            string token = GetToken();
            if (token != null)
            {
                string infos = Jose.JWT.Payload(token);
                JwtAuthObject info = (JwtAuthObject)JsonToObject.JsonTObj(infos, typeof(JwtAuthObject));
                return info.LoginID;
            }
            else
                return 0;
        }
        /// <summary>
        /// 或得token令牌
        /// </summary>
        /// <returns></returns>
        protected string GetToken()
        {
            return Request.Headers.Authorization.Parameter;            
        }
        /// <summary>
        /// 根据用户id获取用户对象
        /// </summary>
        /// <param name="loginId"></param>
        /// <returns></returns>
        protected User GetUserByLoginID(int loginId)
        {
            try
            {
                if (loginId != 0)
                {
                    string sql = "select * from User_tb where login_id=" + loginId;
                    SQLCommand sc = new SQLCommand(sql);
                    DataTable dt = sc.ExecuteScalars();
                    if (dt == null)
                        return null;
                    else
                    {
                        return DataTableToList<User>(dt)[0];
                    }
                }
                else
                    return null;
            }
            catch (Exception e)
            {
                WriteLog("GetUserByLoginID", e.Message);
                return null;
            }
            
        }
        #endregion

        protected PC GetPC(int pcid)
        {
            SQLCommand sc = new SQLCommand("select * from PC_tb where pc_id=@id", "@id", pcid);
            DataRow dr = sc.ExecuteOneRow();
            if (dr == null)
            {
                WriteLog("GetPC", "没有对应流程");
                throw new Exception("没有对应流程");
            }
            return DataRowToObject<PC>(dr);
        }

        protected string GetPCName(int pcid)
        {
            SQLCommand sc = new SQLCommand("select path from PC_tb where pc_id=@pcid", "@pcid", pcid);
            string pcName= sc.ExecuteScalar();
            if (pcName == null)
            {
                WriteLog("GetPCName", "没有找到相应流程名");
                throw new Exception("没有找到相应流程名");
            }
            return pcName;
        }
        /// <summary>
        /// 获取工作路径
        /// </summary>
        /// <param name="pcName">流程名(订单名或者样式名)</param>
        /// <returns></returns>
        protected string GetPCPath(string pcName)
        {
            return m_buyiRoot + "\\buyiWork\\" + pcName;
        }

        protected string GetPCPath(int pcid)
        {
            return m_buyiRoot + "\\buyiWork\\" + GetPCName(pcid);
        }

        //根据样式ID,获得款式目录
        protected string GetStylePath(int model)
        {
            string sql = "select style_time, Style_tb.name as styleName from Model_tb join Style_tb on Model_tb.style_id=Style_tb.style_id where Model_tb.id=@model";
            SQLCommand sc = new SQLCommand(sql, "@model", model);
            DataTable dt = sc.ExecuteScalars();
            if (dt != null)
                return string.Format("{0}\\buyiStyle\\{1}\\{2}",  m_buyiRoot, dt.Rows[0]["style_time"].ToString(), dt.Rows[0]["styleName"].ToString());
            else
                return "";
        }
        #region 文件的相关操作
            
        #endregion

        #region  文件夹的相关操作
           /// <summary>  
        /// 移动文件夹中的所有文件夹与文件到另一个文件夹  
        /// </summary>  
        /// <param name="sourcePath">源文件夹</param>  
        /// <param name="destPath">目标文件夹</param>  
        protected void MoveFolder(string sourcePath, string destPath)
        {
            if (Directory.Exists(sourcePath))
            {
                if (!Directory.Exists(destPath))
                {
                    //目标目录不存在则创建  
                    try
                    {
                        Directory.CreateDirectory(destPath);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("创建目标目录失败：" + ex.Message);
                    }
                }
                //获得源文件下所有文件  
                List<string> files = new List<string>(Directory.GetFiles(sourcePath));
                files.ForEach(c =>
                {
                    string destFile = Path.Combine(new string[] { destPath, Path.GetFileName(c) });
                    //覆盖模式  
                    if (File.Exists(destFile))
                    {
                        File.Delete(destFile);
                    }
                    File.Move(c, destFile);
                });
                //获得源文件下所有目录文件  
                List<string> folders = new List<string>(Directory.GetDirectories(sourcePath));

                folders.ForEach(c =>
                {
                    string destDir = Path.Combine(new string[] { destPath, Path.GetFileName(c) });
                    //Directory.Move必须要在同一个根目录下移动才有效，不能在不同卷中移动。  
                    //Directory.Move(c, destDir);  
                    
                    //采用递归的方法实现  
                    MoveFolder(c, destDir);
                    Directory.Delete(c);
                });
            }
            else
            {
                throw new DirectoryNotFoundException("源目录不存在,"+sourcePath);
            }
        }
        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="root"></param>
        /// <param name="sub">子目录名</param>
        /// <param name="deep">建立几级子目录</param>
        protected void CreateDir(string root, string[] sub, int deep)
        {
            try
            {
                string str = "";
                for (int i = 0; i < deep; i++)
                {
                    if (i == 0)
                        str = "\\" + sub[i];
                    else
                        str += "\\" + sub[i];
                    Directory.CreateDirectory(root + str);
                }
            }
            catch (Exception e)
            {
                WriteLog("CreateDir", e.Message);
            }

        }

        /// <summary>
        /// 删除文件夹以及文件夹下的所有目录结构
        /// </summary>
        /// <param name="dirPath"></param>        
        protected void DeleteFolder(string dirPath)
        {
            if (Directory.Exists(dirPath))
            {
                foreach (string content in Directory.GetFileSystemEntries(dirPath))
                {
                    if (Directory.Exists(content))
                    {
                        Directory.Delete(content, true);
                    }
                    else if (File.Exists(content))
                    {
                        File.Delete(content);
                    }
                }
            }
        }
        #endregion


        #region  流程控制
        
       
        #endregion

        #region 公共函数
        /// <summary>
        /// 获得一个新的唯一ID
        /// </summary>
        /// <returns></returns>
        protected int GetNewSafeID(int loginid)
        {
            SQLCommand sc = new SQLCommand("insert into SafeID_tb(user_id) values(@uid)", "@uid", loginid);
            
            sc.ExecuteNonQuery();
            sc = new SQLCommand("select top 1 id from SafeID_tb where user_id=@uid order by id desc", "@uid", loginid);
            int res = Convert.ToInt32(sc.ExecuteScalar());
            sc = new SQLCommand("delete from SafeID_tb where user_id=@uid", "@uid", loginid);
            sc.ExecuteNonQuery();
            return res;
        }
        /// <summary>
        /// 判断该工序是属于大货流程还是改款流程
        /// </summary>大货：42-48(成衣)  33-37(团订) 改款：11-18(成衣) 22-27(团订)
        /// <param name="code"></param>
        /// <returns>true 大货 false改款</returns>
        protected bool IsOrder(int code)
        {
            if (code >= 33)
                return true;//表示大货
            else
                return false;
        }
 
 
        #endregion
    
        /// <summary>
        /// 写日志文件
        /// </summary> 
        /// <param name="msg"></param>
        /// <param name="loginid">当前登陆者工号</param>
        protected void WriteLog(string currentFun,string msg)
        {
            try
            {
                string filename = m_buyiRoot + "\\buyiHistory\\error.log";
                if (File.Exists(filename))
                {
                    using (FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write))
                    {
                        using (StreamWriter sw = new StreamWriter(fs,Encoding.UTF8))
                        {
                            sw.Write("【" + DateTime.Now + "】【" + currentFun + "】\r\r\r\r  " + msg + "\r\n");
                        }
                    }
                }
                else
                {
                    using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
                    {
                        using (StreamWriter sw = new StreamWriter(fs,Encoding.UTF8))
                        {
                            sw.Write("【" + DateTime.Now + "】【" + currentFun + "】\r\r\r\r  " + msg + "\r\n");
                        }
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 内部调试
        /// </summary>
        /// <param name="currentFun"></param>
        /// <param name="msg"></param>
        protected void WriteDebug(string currentFun,string msg)
        {
            SQLCommand sc = new SQLCommand("select key_val from System_tb where key_name='WriteDebug'");
            string write = sc.ExecuteScalar();
            if (write!=null && write == "y" )
            {
                try
                {
                    string filename = m_buyiRoot + "\\buyiUpload\\debug.log";
                    if (File.Exists(filename))
                    {
                        using (FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write))
                        {
                            using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
                            {
                                sw.Write("【" + DateTime.Now + "】【" + currentFun + "】\r\r\r\r  " + msg + "\r\n");
                            }
                        }
                    }
                    else
                    {
                        using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
                        {
                            using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
                            {
                                sw.Write("【" + DateTime.Now + "】【" + currentFun + "】\r\r\r\r  " + msg + "\r\n");
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
    }
}
